﻿
using Furion;
using Furion.ConfigurableOptions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.Reflection;
using VOL.RabbitMq.RabbitMq;

namespace VOL.RabbitMq;


/// <summary>
/// RabbitMq全局配置
/// </summary>
public static class RabbitMqSetting
{

    public static IConfiguration Configuration { get; private set; }
    public static IServiceCollection _services { get; private set; }


    public static RabbitMqModel RabbitMq { get; private set; }

    public static void RabbitInit()
    {


        //services.Configure<RabbitMqModel>(configuration.GetSection("RabbitMq"));
        // 启用RabbitMq连接

        var options = App.GetConfig<RabbitMqModel>("RabbitMq", true);


        var hendlelist = options.RabbitMqHandler;
        foreach (var item in hendlelist)
        {

        }


        var client = App.GetService<RabbitMqClient>();

        if (!client.IsConnected)
        {
            var con = client.ConnectAsync();
        }
        //启动消费监听
        var ListenList = options.Consumers;
        foreach (var item in ListenList)
        {
            client.SubscribeAsync(item.ExchangeName, item.RoutingKey, item.AutoAck);
        }

    }

}

public class RabbitMqModel : IConfigurableOptions
{

    /// <summary>
    /// 是否启用生产
    /// </summary>
    public bool UseProducer { get; set; }

    /// <summary>
    /// RabbitMq服务主要属性
    /// </summary>
    public RabbitMqOptionDto RabbitOptions { get; set; }

    /// <summary>
    /// 是否使用消费者
    /// </summary>
    public bool UseConsumer { get; set; }


    /// <summary>
    /// 事件拦截器处理
    /// </summary>
    public List<HandlerDto> RabbitMqHandler { get; set; }


    /// <summary>
    /// 消费订阅合集
    /// </summary>
    public List<ConsumersDto> Consumers { get; set; }

}


/// <summary>
/// RabbitMq基本信息
/// </summary>
public class RabbitMqOptionDto
{


    public string Server { get; set; }

    public int Port { get; set; }

    public string ClientId { get; set; }


    public string UserName { get; set; }


    public string Password { get; set; }
}


/// <summary>
/// 拦截器
/// </summary>
public class HandlerDto
{
    /// <summary>
    /// 类库
    /// </summary>
    public string NameSpace { get; set; }


    /// <summary>
    /// 拦截器类名
    /// </summary>
    public string Handler { get; set; }


    /// <summary>
    /// 处理器类型
    /// </summary>
    public Type HandlerType => Assembly.Load(NameSpace).GetType($"{NameSpace}.{Handler}");

}


public class ConsumersDto
{

    /// <summary>
    /// 交换机
    /// </summary>
    public string ExchangeName { get; set; }


    /// <summary>
    /// 路由器
    /// </summary>
    public string RoutingKey { get; set; }

    /// <summary>
    /// 是否做应答处理
    /// </summary>
    public bool AutoAck { get; set; }
}